using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SHFK.B2C.YouZanYun.Network;
using SHKF.B2C.BLL;
using SHKF.B2C.BLL.Center;
using SHKF.B2C.Hosted; 
using SHKF.B2C.MQBase;
using SHKF.B2C.MQBase.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SHKF.B2C.YouZanYun.Consumer
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                var host = Host.CreateDefaultBuilder()
                    .UseRun("json/dbServer.json,json/mq.json")
                    .ConfigureServices((context, services) => {

                        services.Configure<MQConfig>(context.Configuration.GetSection("MQConfig")); 

                        services.AddTransient<RabbitMqCore>();
                        services.AddTransient<ShopMapBLL>();
                        services.AddTransient<ProductInfoBLL>();
                        services.AddTransient<WorkingCenterBLL>();

                        string urlErp = context.Configuration["urlYouZanYun"];
                        HttpClientYouZanYun httpClientYouZanYun = new HttpClientYouZanYun(urlErp); 
                        services.AddSingleton(httpClientYouZanYun);
                        services.AddHostedService<UpdateStockHostedService>();

                    })
                    .Build();
                host.Run();
            }
            catch (Exception ex)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "run.log";
                System.IO.File.AppendAllText(path, $"{DateTime.Now}: {ex.Message}");
            }
        }

        private static void WriteRunLog(string context)
        {
            string root = AppDomain.CurrentDomain.BaseDirectory;
            string runPath = root + "run";

            if (!System.IO.Directory.Exists(runPath))
            {
                Directory.CreateDirectory(runPath);
            }
            string path = $"{runPath}\\{DateTime.Now.ToString("yyyy-MM-dd")}.log";
            System.IO.File.AppendAllText(path, $"{DateTime.Now} {context}\r\n");

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
